package com.shark.teach;

import com.fasterxml.jackson.datatype.jsr310.deser.key.LocalDateKeyDeserializer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther shark
 * @create 2024-08-02 20:36
 */
public class SyncVSLockDemo
{
    public synchronized void m1()
    {
        //暂停几秒钟线程
        System.out.println(Thread.currentThread().getName()+"-----come in");
        try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
    }

    Lock lock = new ReentrantLock(); // ReentrantLock = Re  entrant   Lock
    public void m2()
    {
         if (lock.tryLock())
         {
           try {
               //暂停几秒钟线程
               System.out.println(Thread.currentThread().getName()+"-----come in");
               try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
           } finally {
             lock.unlock();
           }
         } else {
             System.out.println(Thread.currentThread().getName()+"-----lock used....,leave out");
         }
    }

    public void m3() throws InterruptedException
    {
        if (lock.tryLock(3L,TimeUnit.SECONDS))
        {
            try {
                //暂停几秒钟线程
                System.out.println(Thread.currentThread().getName()+"-----come in");
                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName()+"-----lock used....,leave out");
        }
    }

    public void m4() throws InterruptedException
    {
        lock.lock();
        try
        {
            System.out.println("----111111111");
            lock.lock();
            System.out.println("----------22222");
            lock.unlock();
        }finally {
            lock.unlock();
        }
    }


    public static void main(String[] args)
    {
        SyncVSLockDemo syncVSLockDemo = new SyncVSLockDemo();

        new Thread(() -> {
            try {
                syncVSLockDemo.m3();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"t1").start();


        //暂停毫秒
        try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            try {
                syncVSLockDemo.m3();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"t2").start();

    }

}
